package cn.edu.kzjsxy.graduationproject.service.impl;

import cn.edu.kzjsxy.graduationproject.common.Page;
import cn.edu.kzjsxy.graduationproject.common.Result;
import cn.edu.kzjsxy.graduationproject.common.TokenUtil;
import cn.edu.kzjsxy.graduationproject.entity.Buildings;
import cn.edu.kzjsxy.graduationproject.entity.Units;
import cn.edu.kzjsxy.graduationproject.entity.Users;
import cn.edu.kzjsxy.graduationproject.mapper.UnitsMapper;
import cn.edu.kzjsxy.graduationproject.service.IBuildingsService;
import cn.edu.kzjsxy.graduationproject.service.IUnitsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 单元信息表 服务实现类
 * </p>
 *
 * @author chén jiā jùn
 * @since 2024-04-14
 */
@Service
public class UnitsServiceImpl extends ServiceImpl<UnitsMapper, Units> implements IUnitsService {

//	单元的mapper
	@Autowired
	private UnitsMapper unitsMapper;

//	楼栋的service
	@Autowired
	private IBuildingsService buildingsService;

	//	tokenUitl
	@Autowired
	private TokenUtil tokenUtil;

//    <!-- 根据条件查询单元信息 -->
	@Override
	public List<Units> selectUnitsByCondition(Units units) {
		List<Units> unitsList = unitsMapper.selectUnitsByCondition(units);
		unitsList = getBuildingsName(unitsList);
		return unitsList;
	}

//	分页查询单元信息
	@Override
	public Result<PageInfo<Units>> selectUnitsByPage(Page page, Units units, HttpServletRequest request) {
		Users user = tokenUtil.resolveToken(request);
		if(Objects.equals(user.getRole(), "0")){
			units.setHousemasterId(user.getUserId());
		}
		// 设置分页
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		// 执行查询
		List<Units> unitsList = unitsMapper.selectUnitsByCondition(units);
		unitsList = getBuildingsName(unitsList);
		PageInfo<Units> pageInfo = new PageInfo<>(unitsList);
		return Result.success(pageInfo);
	}

// 查询楼栋名称
	@Override
	public Units getBuildingsName(Units units) {
		if(units!=null){
			Buildings buildings = buildingsService.getById(units.getBuildingId());
			if(buildings!=null){
				units.setBuildingName(buildings.getBuildingName());
			}
		}
		return  units;
	}

//	批量查询楼栋名称
	@Override
	public List<Units> getBuildingsName(List<Units> unitsList) {
		if(unitsList!=null&&!unitsList.isEmpty()){
			for (Units units : unitsList) {
				Buildings buildings = buildingsService.getById(units.getBuildingId());
				if(buildings!=null){
					units.setBuildingName(buildings.getBuildingName());
				}
			}
		}
		return  unitsList;
	}
}
